'use client'

import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { useAuth } from '@/contexts/auth-context'
import { ToolCard } from './tool-card'
import { ToolGridSkeleton } from './tool-card-skeleton'
import type { Tool, Category, User } from '@/types'

interface ToolWithRelations extends Tool {
  category: Category
  user: Pick<User, 'name' | 'avatar'>
  _count?: {
    reviews: number
    favorites: number
  }
}

export function ToolGrid() {
  const [tools, setTools] = useState<ToolWithRelations[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const searchParams = useSearchParams()
  const { user } = useAuth()

  useEffect(() => {
    const fetchTools = async () => {
      try {
        setLoading(true)
        const params = new URLSearchParams()

        const category = searchParams.get('category')
        const search = searchParams.get('q')

        if (category) params.set('category', category)
        if (search) params.set('q', search)

        // 如果用户已登录，包含用户自己的工具
        if (user) {
          params.set('userId', user.id)
          params.set('includeOwn', 'true')
        }

        const response = await fetch(`/api/tools?${params.toString()}`)
        const result = await response.json()

        if (!response.ok) {
          throw new Error(result.error || '获取工具列表失败')
        }

        setTools(result.data || [])
      } catch (err: any) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }

    fetchTools()
  }, [searchParams, user])

  if (loading) {
    return <ToolGridSkeleton />
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <div className="max-w-md mx-auto">
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            加载失败
          </h3>
          <p className="text-gray-500 mb-6">
            {error}
          </p>
          <button
            onClick={() => window.location.reload()}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    )
  }

  if (tools.length === 0) {
    return (
      <div className="text-center py-12">
        <div className="max-w-md mx-auto">
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无工具
          </h3>
          <p className="text-gray-500 mb-6">
            还没有发布的工具，成为第一个分享者吧！
          </p>
          <a
            href="/tools/new"
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            发布工具
          </a>
        </div>
      </div>
    )
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
      {tools.map((tool) => (
        <ToolCard key={tool.id} tool={tool} />
      ))}
    </div>
  )
}
